package cn.edu.szu.bigdata.util;

import net.ipip.ipdb.*;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.UnknownHostException;

public class IPDataHandler {
    private static String default_IP_DATA_PATH = "C:\\Users\\longhao\\IdeaProjects\\xintu\\data\\ipipfree.ipdb";
    private static City cityDb;
    private IPDataHandler() {

    }

    public static void initIPData(String IP_DATA_PATH) {
        if (IP_DATA_PATH == null) {
            IP_DATA_PATH = default_IP_DATA_PATH;
        }
        try {
            cityDb = new City(IP_DATA_PATH);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static CityInfo findGeography(String address) {
        CityInfo cityInfo = null;
        if (cityDb==null){
            System.out.println("IP数据库未加载");
            return null;
        }
        if (address != null && address.length() != 0) {
            String ip = "127.0.0.1";
            try {
                ip = Inet4Address.getByName(address).getHostAddress();
            } catch (UnknownHostException var17) {
                var17.printStackTrace();
            }
            try {
                cityInfo = cityDb.findCity(ip, "CN");
            } catch (IPFormatException e) {
                System.out.println("IP 格式错误");
            } catch (InvalidDatabaseException e) {
                System.out.println("不正确的IP数据库");
            }
        }
        return cityInfo;
    }

    public static void main(String[] args) {
        IPDataHandler.initIPData(null);
        CityInfo cityInfo=IPDataHandler.findGeography("192.168.1.1");
        System.out.println(cityInfo);
    }
}
